package com.bawei.park2302.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_base.utils.utils.entity.NoticeBeanItem
import com.bawei.lib_base.utils.utils.entity.UserBean
import com.bawei.lib_base.utils.utils.mvi.BaseActivity
import com.bawei.lib_base.utils.utils.mvi.UiState
import com.bawei.lib_base.utils.utils.utils.Cons
import com.bawei.park2302.R
import com.bawei.park2302.databinding.ActivityLoginBinding
import com.blankj.utilcode.util.SPUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/app/LoginActivity")
@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding,UserIntent,UserViewModel>() {
    override val binding: ActivityLoginBinding by lazy {
        ActivityLoginBinding.inflate(layoutInflater)
    }
    override val vm: UserViewModel by viewModels<UserViewModel>()

    @Autowired
    @JvmField
    var username = ""
    @Autowired
    @JvmField
    var password = ""
    override fun initView() {
        ARouter.getInstance().inject(this)
        val token = SPUtils.getInstance().getString(Cons.TOKEN, "")
        if(token.isNotEmpty()){
            ARouter.getInstance().build("/app/HomeActivity").navigation()
            finish()
            return
        }

        binding.loginUsername.setText(username)

        binding.loginPassword.setText(password)

        binding.btnLogin.setOnClickListener {
            val username = binding.loginUsername.text.toString()
            val password = binding.loginPassword.text.toString()

            vm.sendIntent(UserIntent.login(username,password))
        }

        //点击跳转到注册
        binding.tvSignAccount.setOnClickListener {
            ARouter.getInstance().build("/app/RegisterActivity").navigation()
        }
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        ARouter.getInstance().build("/app/HomeActivity").navigation()
                        val bean = it.data as UserBean
                        SPUtils.getInstance().apply {
                            put(Cons.TOKEN,bean.token)
                            put(Cons.USERNAME,bean.username)
                            put(Cons.UID,bean.id)
                            put(Cons.ROLE,bean.roleid)
                        }
                    }

                    else -> {}
                }
            }
        }
    }
}